<template>
  <div class="page" :style="pageHeight">
    <div style="height: 170px"></div>
    <div id="logo" style="text-align: center; margin-top: 0">
      <img
        src="../assets/logo.png" height="80" width="220"
        style="margin-top: 5px"
      />
    </div>
    <el-col
      :xs="{span:22,offset:1}"
      :sm="{span:16,offset:4}"
      :md="{span:8,offset:8}"
      class="login">
      <el-form
        :model="form"
        status-icon
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm">
        <el-form-item label="工号" prop="name">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login"
                     style="width: 200px; position: relative; left: 50px">登录</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </div>
</template>

<script>
export default {
  name: 'Login',
  created() {
    const store = JSON.parse(localStorage.getItem('store'));
    if (store) {
      const { token } = store;
      if (token) {
        this.$router.push('/home/welcome');
      }
    }
    this.resize();
  },
  mounted() {
    window.addEventListener('resize', this.resize);
  },
  data() {
    return {
      pageHeight: {
        height: '',
      },
      form: {
        username: '',
        password: '',
      },
    };
  },
  computed: {
    token() {
      return this.$store.state.token;
    },
  },
  methods: {
    resize() {
      this.pageHeight.height = `${window.innerHeight}px`;
    },
    login() {
      localStorage.setItem('store', JSON.stringify(this.$store.state));
      this.axios.post('/api/token/', this.form)
        .then((response) => {
          const token = response.data.access;
          console.log(response.data);
          const { username } = this.form;
          this.$store.dispatch('saveToken', token);
          this.$store.dispatch('saveUsername', username);
          localStorage.setItem('store', JSON.stringify(this.$store.state));
          this.$router.push('/home/welcome');
        })
        .catch((error) => {
          console.log(error);
          alert('用户名或密码错误');
        });
    },
  },
};
</script>

<style scoped lang="scss">
.login {
  margin-top: 40px;
  background-color: aliceblue;
  padding-right: 80px;
  padding-top: 40px;
  border: 1px solid lightblue;
  box-shadow: 2px 2px 2px lightblue;
}
.page {
  background-image:url("../assets/login_backgorund.jpg");
  background-size: cover;
}
</style>
